import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xindong/common/xindong_define.dart';
import 'package:xindong/routes/tab_moments/controller/xindong_dongtai_vm.dart';
import 'package:xindong/routes/tab_moments/view/xindong_dongtai_list_container.dart';

class XinDongDongTaiTabController extends GetxController {
  static XinDongDongTaiTabController get to => Get.find();

  static const String kControllerTagRecommend = "kControllerTagRecommend";
  static const String kControllerTagFollow = "kControllerTagFollow";

  late int currentIndex = 0;
  late TabController tabController;
  XinDongDongTaiVM? recommendVM;
  XinDongDongTaiVM? followVM;

  // Tab
  List<Widget> tabBar() {
    return [const Tab(text: "推荐"), const Tab(text: "关注")];
  }

  // TabView
  List<Widget> tabBarViews() {
    return [
      const XinDongDongTaiListContainer(
        controllerTag: kControllerTagRecommend,
        emptyTips: '最近没有新动态',
      ),
      const XinDongDongTaiListContainer(
        controllerTag: kControllerTagFollow,
        emptyTips: '去关注更多的人，获取ta的最新动态',
      ),
    ];
  }

  // 初始化
  void initWithVsync(TickerProvider vsync) {
    tabController = TabController(length: tabBar().length, vsync: vsync);
    tabController.addListener(() {
      updateListener();
    });
    recommendVM = XinDongDongTaiVM(type: 0);
    followVM = XinDongDongTaiVM(type: 1);
    // tag标记同一个控制器名称，区分不同实例
    Get.create(() => recommendVM!, tag: kControllerTagRecommend, permanent: false);
    Get.create(() => followVM!, tag: kControllerTagFollow, permanent: false);
  }

  // TabController监听页面切换
  void updateListener() {
    currentIndex = tabController.index.round();
    update();
  }

  // ScrollNotification监听滚动位置切换
  void updateScrollNotification(double offset) {
    int index = (offset + screenWidth / 2).abs() ~/ screenWidth;
    currentIndex = index;
  }

  // 通知刷新
  void notifyRefresh() {
    if (currentIndex == 0) {
      recommendVM?.notifyRefresh();
    } else if (currentIndex == 1) {
      followVM?.notifyRefresh();
    }
  }
}
